let safeboxDao = module.exports;
let mysqlPool = require('./MySQLPool');

safeboxDao.saveWithTx = async function (conn, record) {
    let sql = 'insert into safebox (uid, amt, create_time)' +
        '                    values (?,  ?,   now())';
    let args = [record.uid, record.amt];
    let res = await conn.query(sql, args);
    if (res){
        return res.insertId;
    }

    return 0;
};

safeboxDao.newWithTx = async function(conn, uid, pwd){
    let sql = 'insert into safebox (uid, amt, pwd, flag, create_time)' +
        '                    values(?,   0,   ?,   1,    now())';
    let args = [uid, pwd];
    let res = await conn.query(sql, args);
    if (res){
        return res.insertId;
    }

    return 0;
};

safeboxDao.updatePwdWithTx = async function(conn, uid, pwd){
    let sql = 'update safebox set pwd = ? where uid = ?';
    let args = [pwd, uid];
    let res = await conn.query(sql, args);
    if (res){
        return res.affectedRows;
    }

    return 0;
};

safeboxDao.updatePwd = async function(uid, pwd){
    let sql = 'update safebox set pwd = ? where uid = ?';
    let args = [pwd, uid];
    let res = await mysqlPool.query(sql, args);
    if (res){
        return res.affectedRows;
    }

    return 0;
};

safeboxDao.getWithTx = async function(conn, uid){
    let sql = 'select * from safebox where uid = ?';
    let args = [uid];
    let res = await conn.query(sql, args);
    if (res && res.length > 0){
        return res[0];
    }

    return null;
};

safeboxDao.get = async function(uid){
    let sql = 'select * from safebox where uid = ? limit 1';
    let args = [uid];
    let res = await mysqlPool.query(sql, args);
    if (res && res.length > 0){
        return res[0];
    }

    return null;
};

safeboxDao.updateWithTx = async function (conn, record) {
    let sql = 'update safebox set amt = (amt + ?) where uid = ? and (amt + ?) >= 0';
    let args = [record.amt, record.uid, record.amt];
    let res = await conn.query(sql, args);
    if (res){
        return res.affectedRows;
    }

    return 0;
};